<template>
  <div class="main-content">
    <div class="panel">
      <div class="panel-header">
        <div class="panel-title">平台分类管理</div>
        <div class="header-controls">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索分类名称或ID"
            style="width: 250px;"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          <el-select v-model="selectedPlatform" placeholder="选择平台" style="width:200px;" @change="handlePlatformChange">
            <el-option v-for="p in platformList" :key="p.id" :label="p.name" :value="p.id" />
          </el-select>

          <el-button type="primary" @click="refreshData" :loading="loading">
            <el-icon><Refresh /></el-icon>
            刷新数据
          </el-button>
          <el-button @click="exportData">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </div>
      </div>
      <div class="panel-body">
        <!-- 数据统计信息 -->
        <div class="stats-bar">
          <div class="stat-item">
            <span class="stat-label">当前平台：</span>
            <span class="stat-value">{{ getCurrentPlatformName() }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">分类总数：</span>
            <span class="stat-value">{{ totalCount }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">显示数量：</span>
            <span class="stat-value">{{ displayedCategories.length }}</span>
          </div>
          <div class="stat-item">
            <span class="stat-label">最后更新：</span>
            <span class="stat-value">{{ lastUpdateTime }}</span>
          </div>
        </div>

        <!-- 统一的表格显示 -->
        <el-table
          :data="displayedCategories"
          style="width:100%"
          border
          stripe
          row-key="id"
          :tree-props="isTreeView ? { children: 'children' } : undefined"
          v-loading="loading"
          element-loading-text="加载中..."
          :default-expand-all="false"
          :expand-row-keys="expandedKeys"
          @expand-change="handleExpandChange"
        >
          <el-table-column prop="id" label="类目ID" width="150" sortable>
            <template #default="scope">
              <el-tag size="small" type="info">{{ scope.row.id }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="name" label="类目名称" min-width="200" show-overflow-tooltip>
            <template #default="scope">
              <div class="category-name">
                <span>{{ scope.row.name }}</span>
                <el-tag v-if="scope.row.children && scope.row.children.length" size="small" type="success" style="margin-left: 8px;">
                  {{ scope.row.children.length }}个子分类
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="parentId" label="父级ID" width="150" sortable>
            <template #default="scope">
              <el-tag v-if="scope.row.parentId" size="small" type="warning">{{ scope.row.parentId }}</el-tag>
              <span v-else style="color: #909399;">顶级分类</span>
            </template>
          </el-table-column>
          <el-table-column label="层级" width="80" align="center">
            <template #default="scope">
              <el-tag size="small" :type="getLevelTagType(scope.row.level)">
                {{ scope.row.level || 1 }}级
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="Logo" width="120" align="center">
            <template #default="scope">
              <div class="logo-container">
                <div v-if="scope.row.logo" class="logo-display">
                  <img :src="scope.row.logo" alt="logo" class="logo-image" />
                  <el-button size="small" type="danger" link @click="removeLogo(scope.row)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
                <el-button v-else size="small" type="primary" link @click="uploadLogo(scope.row)">
                  <el-icon><Upload /></el-icon>
                  上传Logo
                </el-button>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="120" align="center">
            <template #default="scope">
              <el-button size="small" type="primary" link @click="copyToClipboard(scope.row)">
                <el-icon><CopyDocument /></el-icon>
                复制ID
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- Logo上传对话框 -->
        <el-dialog v-model="logoDialogVisible" title="上传分类Logo" width="500px">
          <div class="logo-upload-container">
            <div class="upload-area">
              <el-upload
                ref="uploadRef"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleLogoChange"
                accept="image/*"
                drag
              >
                <div class="upload-content">
                  <el-icon class="upload-icon"><Upload /></el-icon>
                  <div class="upload-text">
                    <span>点击或拖拽图片到此处上传</span>
                    <span class="upload-tip">支持 JPG、PNG、GIF 格式，建议尺寸 100x100px</span>
                  </div>
                </div>
              </el-upload>
            </div>
            
            <div v-if="tempLogoUrl" class="preview-area">
              <div class="preview-title">预览效果：</div>
              <div class="preview-image">
                <img :src="tempLogoUrl" alt="logo preview" />
              </div>
            </div>
          </div>
          
          <template #footer>
            <el-button @click="cancelLogoUpload">取消</el-button>
            <el-button type="primary" @click="confirmLogoUpload" :disabled="!tempLogoUrl">
              确认上传
            </el-button>
          </template>
        </el-dialog>

      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, CopyDocument, Upload, Delete } from '@element-plus/icons-vue'
import * as XLSX from 'xlsx'

// 平台列表
const platformList = [
  { id: 'mercari', name: '煤炉' },
  { id: 'yahoo_used', name: '雅虎闲置' },
  { id: 'yahoo_auction', name: '雅虎日拍' },
  { id: 'rakuma', name: '乐天闲置' },
]

// 响应式数据
const selectedPlatform = ref(platformList[0].id)
const searchKeyword = ref('')
const loading = ref(false)
const expandedKeys = ref<string[]>([])
const lastUpdateTime = ref('2024-01-15 14:30:25')

// Logo上传相关
const logoDialogVisible = ref(false)
const tempLogoUrl = ref('')
const currentCategory = ref<Category | null>(null)

// 分类数据类型定义
type Category = {
  id: string;
  name: string;
  parentId: string;
  platform: string;
  level?: number;
  children?: Category[];
  logo?: string;
}

// mock 映射关系（实际应从PlatformMapping获取）
type Mapping = { platform: string; platformCategoryId: string; localCategoryId: string; localCategoryName: string }
const mappingList = ref<Mapping[]>([])
function autoGenerateMappings() {
  // 只为偶数下标的分类生成映射
  const cats = categories.value.filter(c => c.platform === selectedPlatform.value)
  mappingList.value = cats
    .filter((cat, idx) => idx % 2 === 0) // 只映射偶数下标
    .map((cat, idx) => ({
      platform: cat.platform,
      platformCategoryId: cat.id,
      localCategoryId: String(100 + idx),
      localCategoryName: `系统分类${100 + idx}`
    }))
}
// 页面加载和平台切换时自动生成映射
onMounted(autoGenerateMappings)
watch(selectedPlatform, autoGenerateMappings)
function isMapped(row: Category) {
  return mappingList.value.some(m => m.platform === row.platform && m.platformCategoryId === row.id)
}
function getMapping(row: Category): { localCategoryId?: string, localCategoryName?: string } {
  return mappingList.value.find(m => m.platform === row.platform && m.platformCategoryId === row.id) as { localCategoryId?: string, localCategoryName?: string } || {}
}

// 生成模拟的日本网站抓取数据
function generateMockCategories(): Category[] {
  const result: Category[] = []
  let idCounter = 1000

  // 煤炉平台 - 树形结构
  for (let i = 1; i <= 8; i++) {
    const topId = (idCounter++).toString()
    const top: Category = {
              id: topId,
        name: `${getCategoryName(i)}`,
        parentId: '',
        platform: 'mercari',
        level: 1,
        children: [],
        logo: i === 1 ? '' : undefined
    }

    for (let j = 1; j <= 8; j++) {
      const secId = (idCounter++).toString()
      const sec: Category = {
        id: secId,
        name: `${getCategoryName(i)} - ${getSubCategoryName(j)}`,
        parentId: topId,
        platform: 'mercari',
        level: 2,
        children: []
      }

      for (let k = 1; k <= 6; k++) {
        const thirdId = (idCounter++).toString()
        sec.children!.push({
          id: thirdId,
          name: `${getSubCategoryName(j)} - ${getDetailCategoryName(k)}`,
          parentId: secId,
          platform: 'mercari',
          level: 3
        })
      }
      top.children!.push(sec)
    }
    result.push(top)
  }

  // 其他平台 - 平铺结构
  const otherPlatforms = [
    { platform: 'yahoo_used', categories: ['个护健康', '美容护肤', '母婴用品', '家居生活', '运动户外'] },
    { platform: 'yahoo_auction', categories: ['电子产品', '动漫周边', '收藏品', '古董文物', '艺术品'] },
    { platform: 'rakuma', categories: ['服装配饰', '鞋包配件', '珠宝首饰', '手表眼镜', '数码配件'] }
  ]

  otherPlatforms.forEach(({ platform, categories: cats }) => {
    cats.forEach((name, index) => {
      result.push({
        id: `${platform}_${index + 1}`,
        name,
        parentId: '',
        platform,
        level: 1,
        logo: index === 0 ? '' : undefined
      })
    })
  })

  return result
}

// 分类名称生成函数
function getCategoryName(index: number): string {
  const names = ['服装配饰', '电子产品', '家居生活', '美容护肤', '运动户外', '母婴用品', '图书音像', '食品保健']
  return names[index - 1] || `分类${index}`
}

function getSubCategoryName(index: number): string {
  const names = ['男装', '女装', '童装', '内衣', '鞋靴', '箱包', '配饰', '其他']
  return names[index - 1] || `子分类${index}`
}

function getDetailCategoryName(index: number): string {
  const names = ['上衣', '下装', '套装', '外套', '连衣裙', '其他']
  return names[index - 1] || `详细分类${index}`
}

const categories = ref(generateMockCategories())
// 计算属性
function filterTreeByMappingStatus(nodes: Category[], status: string): Category[] {
  // status: 'all' | 'mapped' | 'unmapped'
  if (status === 'all') return nodes
  const result: Category[] = []
  for (const node of nodes) {
    let children: Category[] = []
    if (node.children && node.children.length) {
      children = filterTreeByMappingStatus(node.children, status)
    }
    const mapped = isMapped(node)
    const match = (status === 'mapped' && mapped) || (status === 'unmapped' && !mapped)
    // 只保留：1.自己符合条件 2.有子节点符合条件
    if (match || children.length > 0) {
      result.push({ ...node, children })
    }
  }
  return result
}
const filteredCategories = computed(() => {
  let result = categories.value.filter(c => c.platform === selectedPlatform.value)

  if (selectedPlatform.value === 'mercari') {
    if (searchKeyword.value.trim()) {
      // 搜索时展平所有匹配的节点
      const keyword = searchKeyword.value.toLowerCase()
      function flattenSearchResults(nodes: Category[]): Category[] {
        let arr: Category[] = []
        for (const n of nodes) {
          const nodeMatches = n.id.toLowerCase().includes(keyword) || 
                             n.name.toLowerCase().includes(keyword)
          if (nodeMatches) arr.push({ ...n, children: undefined })
          if (n.children && n.children.length) {
            arr = arr.concat(flattenSearchResults(n.children))
          }
        }
        return arr
      }
      return flattenSearchResults(result.filter(c => !c.parentId))

    } else {
      // 默认树形结构
      let roots = result.filter(c => !c.parentId)
      return roots
    }
  } else {
    // 平铺结构
    if (searchKeyword.value.trim()) {
      // 搜索过滤
      const keyword = searchKeyword.value.toLowerCase()
      result = result.filter(c =>
        c.id.toLowerCase().includes(keyword) ||
        c.name.toLowerCase().includes(keyword)
      )
    }

    return result
  }
})

// 显示的分类数据
const displayedCategories = computed(() => {
  return filteredCategories.value
})

// 是否为树形视图
const isTreeView = computed(() => {
  // 煤炉平台且没有搜索关键词时才显示树形结构
  return selectedPlatform.value === 'mercari' && !searchKeyword.value.trim()
})

// 总数统计
const totalCount = computed(() => {
  return categories.value.filter(c => c.platform === selectedPlatform.value).length
})

// 功能函数
function getCurrentPlatformName(): string {
  return platformList.find(p => p.id === selectedPlatform.value)?.name || ''
}

function handleSearch() {
  // 搜索功能，实时过滤
}

function handlePlatformChange() {
  searchKeyword.value = '' // 切换平台时清空搜索
  expandedKeys.value = []
}

function refreshData() {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    lastUpdateTime.value = new Date().toLocaleString('zh-CN')
    loading.value = false
    ElMessage.success('数据刷新成功')
  }, 1000)
}

function exportData() {
  const data = filteredCategories.value
  const excelData = generateExcelData(data)
  downloadExcel(excelData, `${getCurrentPlatformName()}_分类数据.xlsx`)
  ElMessage.success('数据导出成功')
}

function generateExcelData(data: Category[]): any[][] {
  const headers = ['类目ID', '类目名称', '父级ID', '层级']
  const rows = [headers]

  function addRows(categories: Category[], level = 1) {
    categories.forEach(cat => {
      rows.push([
        cat.id,
        cat.name,
        cat.parentId || '',
        level.toString()
      ])

      if (cat.children && cat.children.length > 0) {
        addRows(cat.children, level + 1)
      }
    })
  }

  addRows(data)
  return rows
}

function downloadExcel(data: any[][], filename: string) {
  // 创建工作表
  const ws = XLSX.utils.aoa_to_sheet(data)
  
  // 设置列宽
  const colWidths = [
    { wch: 15 }, // 类目ID
    { wch: 20 }, // 类目名称
    { wch: 15 }, // 父级ID
    { wch: 8 }   // 层级
  ]
  ws['!cols'] = colWidths
  
  // 创建工作簿
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '分类数据')
  
  // 导出文件
  XLSX.writeFile(wb, filename)
}

function copyToClipboard(row: Category) {
  navigator.clipboard.writeText(row.id).then(() => {
    ElMessage.success(`已复制ID: ${row.id}`)
  }).catch(() => {
    ElMessage.error('复制失败')
  })
}

function getLevelTagType(level?: number): string {
  switch (level) {
    case 1: return 'primary'
    case 2: return 'success'
    case 3: return 'warning'
    default: return 'info'
  }
}

function handleExpandChange(row: Category, expanded: boolean) {
  if (expanded) {
    expandedKeys.value.push(row.id)
  } else {
    expandedKeys.value = expandedKeys.value.filter(key => key !== row.id)
  }
}

// Logo上传相关方法
function uploadLogo(category: Category) {
  currentCategory.value = category
  logoDialogVisible.value = true
  tempLogoUrl.value = ''
}

function removeLogo(category: Category) {
  ElMessageBox.confirm(
    '确定要删除这个Logo吗？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    category.logo = undefined
    ElMessage.success('Logo删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

function handleLogoChange(file: any) {
  if (file && file.raw) {
    const reader = new FileReader()
    reader.onload = (e) => {
      tempLogoUrl.value = e.target?.result as string
    }
    reader.readAsDataURL(file.raw)
  }
}

function confirmLogoUpload() {
  if (currentCategory.value && tempLogoUrl.value) {
    currentCategory.value.logo = tempLogoUrl.value
    logoDialogVisible.value = false
    tempLogoUrl.value = ''
    currentCategory.value = null
    ElMessage.success('Logo上传成功')
  }
}

function cancelLogoUpload() {
  logoDialogVisible.value = false
  tempLogoUrl.value = ''
  currentCategory.value = null
}



// 生命周期
onMounted(() => {
  // 组件挂载时可以调用API获取最新数据
  console.log('平台分类管理页面已加载')
})
</script>

<style scoped>
.main-content {
  min-height: 100vh;
  background: #f5f6fa;
  width: 100%;
  padding: 0;
}

.panel {
  background: #fff;
  border-radius: 0;
  box-shadow: none;
  margin: 0;
  width: 100%;
}

.panel-header {
  padding: 20px 32px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
}

.panel-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.header-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.panel-body {
  padding: 24px 32px;
  width: 100%;
  box-sizing: border-box;
}

/* 统计信息栏 */
.stats-bar {
  display: flex;
  gap: 32px;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.stat-value {
  font-size: 14px;
  color: #409eff;
  font-weight: 600;
}

/* 分类名称样式 */
.category-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 自定义分页样式 */
.custom-pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
  margin-top: 24px;
  padding: 20px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  border: 1px solid #e4e7ed;
}

.pagination-info {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.pagination-size {
  display: flex;
  align-items: center;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 32px;
  height: 32px;
  padding: 0 8px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  background: #fff;
  color: #606266;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s;
  user-select: none;
}

.pagination-btn:hover:not(:disabled) {
  border-color: #409eff;
  color: #409eff;
}

.pagination-btn:disabled {
  background: #f5f7fa;
  border-color: #e4e7ed;
  color: #c0c4cc;
  cursor: not-allowed;
}

.pagination-btn.active {
  background: #409eff;
  border-color: #409eff;
  color: #fff;
}

.pagination-btn.active:hover {
  background: #66b1ff;
  border-color: #66b1ff;
}

.pagination-pages {
  display: flex;
  align-items: center;
  gap: 4px;
}

.pagination-ellipsis {
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 32px;
  height: 32px;
  color: #c0c4cc;
  font-size: 14px;
  user-select: none;
}

.pagination-jumper {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
  color: #606266;
}

.pagination-jumper .el-input {
  text-align: center;
}

.pagination-jumper .el-input :deep(.el-input__inner) {
  text-align: center;
  padding: 0 8px;
}

/* 表格优化 */
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background-color: #fafafa;
}

:deep(.el-table__header th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table__row:hover > td) {
  background-color: #f5f7fa;
}

/* Logo相关样式 */
.logo-container {
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-display {
  display: flex;
  align-items: center;
  gap: 8px;
}

.logo-image {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  object-fit: cover;
  border: 1px solid #e4e7ed;
}

.logo-upload-container {
  padding: 20px 0;
}

.upload-area {
  margin-bottom: 20px;
}

.upload-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 40px 20px;
}

.upload-icon {
  font-size: 48px;
  color: #c0c4cc;
}

.upload-text {
  text-align: center;
  color: #606266;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.preview-area {
  margin-top: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
}

.preview-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 12px;
}

.preview-image {
  display: flex;
  justify-content: center;
}

.preview-image img {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  border: 2px solid #e4e7ed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .panel-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .header-controls {
    flex-wrap: wrap;
    gap: 8px;
  }

  .stats-bar {
    flex-direction: column;
    gap: 12px;
  }

  .panel-body {
    padding: 16px;
  }

  .custom-pagination {
    flex-direction: column;
    gap: 16px;
    padding: 16px;
  }

  .pagination-controls {
    order: 1;
  }

  .pagination-info {
    order: 2;
  }

  .pagination-size {
    order: 3;
  }

  .pagination-jumper {
    order: 4;
  }
}

@media (max-width: 480px) {
  .custom-pagination {
    gap: 12px;
    padding: 12px;
  }

  .pagination-btn {
    min-width: 28px;
    height: 28px;
    font-size: 12px;
  }

  .pagination-info,
  .pagination-jumper {
    font-size: 12px;
  }
}

/* 强制覆盖样式确保全屏显示 */
.main-content, .panel {
  margin: 0 !important;
  width: 100% !important;
  max-width: 100% !important;
  border-radius: 0 !important;
  box-shadow: none !important;
}
</style>